import { Component, OnInit, Output, EventEmitter, Input, ViewChild, TemplateRef, HostBinding } from '@angular/core';
import { NotifyService } from '@farris/ui-notify';
import { DatagridComponent } from '@farris/ui-datagrid';
import { IdService } from '@farris/ui-common';
import { EditorTypes } from '@farris/ui-datagrid-editors';

/**
 * 智能输入框弹出表单，填写映射 "{'id':'company.company','name':'company.company_Name'}"
 */
@Component({
    selector: 'app-inputgroup-form-mapping-editor',
    templateUrl: './inputgroup-form-mapping-editor.html'
})
export class InputgroupFormMappingEditorComponent implements OnInit {
    @Output() closeModal = new EventEmitter<any>();
    @Output() submitModal = new EventEmitter<any>();

    @Input() value: string;

    @Input() editorParams: any = {};

    @HostBinding('class')
    class = 'd-flex f-utils-fill-flex-column h-100';

    modalConfig = {
        title: '映射编辑器',
        width: 900,
        height: 500,
        showButtons: true
    };

    @ViewChild('itemsFooter') modalFooter: TemplateRef<any>;
    @ViewChild('dg') dg: DatagridComponent;

    // 当前编辑数据
    mapValues = [];

    columns = [
        { field: 'helpLabel', title: '弹出表单字段', editor: { type: EditorTypes.TEXTBOX } },
        { field: 'formLabel', title: '绑定字段', editor: { type: EditorTypes.TEXTBOX } }
    ];

    constructor(private notifyService: NotifyService, private idServ: IdService) { }

    ngOnInit() {
        if (this.value) {
            this.convertMapStr2Array();
        }
    }


    private convertMapStr2Array() {
        let mapObject;
        try {
            const regExp = new RegExp('\'', 'g');
            const value = this.value.replace(regExp, '\"');
            mapObject = JSON.parse(value);
            const helpLabels = Object.keys(mapObject);
            if (helpLabels.length === 0) {
                return;
            }
            helpLabels.forEach(helpLabel => {
                const formLabel = mapObject[helpLabel];
                this.mapValues.push({
                    helpLabel,
                    formLabel,
                    hId: this.idServ.generate()
                });

            });
        } catch (error) {
            this.notifyService.error('mapFields 格式错误！！');
        }


    }

    addItem() {
        // 触发单元格结束编辑
        this.dg.endEditing();

        const newData = this.createData();
        this.dg.appendRow(newData);
    }
    private createData(): any {
        return {
            helpLabel: '',
            formLabel: '',
            hId: this.idServ.generate()
        };

    }

    removeItem() {
        // 触发单元格结束编辑
        this.dg.endEditing();

        const row = this.dg.selectedRow;
        if (row) {
            this.dg.deleteRow(row.id);
            this.dg.clearSelections();
        } else {
            this.notifyService.warning('请选中要删除的行');
        }
    }

    clickCancel() {
        this.closeModal.emit();
    }

    clickConfirm() {
        // 触发单元格结束编辑
        this.dg.endEditing();

        // 获取最新数组
        const latestData = [];
        this.dg.data.forEach(d => {
            const { hId, ...other } = d;
            latestData.push(other);
        });


        // 校验
        if (!this.checkBeforeSave(latestData)) {
            return;
        }


        const mapObject = {};
        latestData.forEach(map => {
            mapObject[map.helpLabel] = map.formLabel;
        });
        let mapStr = JSON.stringify(mapObject);
        const regExp = new RegExp('\"', 'g');
        mapStr = mapStr.replace(regExp, '\'');

        this.submitModal.emit({ value: mapStr });


    }



    /**
     * 保存前检查
     */
    checkBeforeSave(data: any[]): boolean {


        // ② 非空，则校验每个的键值是否为空
        for (const item of data) {
            if (!item.helpLabel) {
                this.notifyService.warning('弹出表单字段不允许为空。');
                return false;
            }
            if (!item.formLabel) {
                this.notifyService.warning('绑定字段不允许为空。');
                return false;
            }

        }

        // ③ 不允许重复
        const helpLabels = data.map(e => e.helpLabel);
        const keySet = new Set(helpLabels);
        const exclusiveKeys = Array.from(keySet);
        if (helpLabels.length !== exclusiveKeys.length) {
            this.notifyService.warning('弹出表单字段不允许重复。');
            return false;
        }

        const formLabels = data.map(e => e.formLabel);
        const keySetForm = new Set(helpLabels);
        const exclusiveKeysForm = Array.from(keySetForm);
        if (formLabels.length !== exclusiveKeysForm.length) {
            this.notifyService.warning('绑定字段字段不允许重复。');
            return false;
        }




        return true;

    }
}
